import React, { Component } from 'react';
import { Col, message, Popover, Row, Table } from 'antd';
import Condition from 'components/condition';
import Importer from 'components/template/importer/index';
import ApplicationApportion from './application-apportion';
import { messages, queryCurrencyPrecision } from 'share/common';

const { If } = Condition;

class ApportionFeatures extends Component {
  component = {
    div: 'div',
    ApplicationApportion
  };

  constructor(props) {
    super(props);
    this.state = {
      tabKey: null,
      btnFeats: [
        {
          key: 'expense',
          show: false,
          btn: [
            {
              span: window.ISIE9 ? 12 : 8,
              show: true,
              type: 'div',
              params: {
                className: 'new-expense-apportion',
                onClick: this.handleNewExpenseApportion
              },
              child: <span>{messages('expense-1.key9')/*新建分摊*/}</span>
            },
            {
              span: 8,
              show: !window.ISIE9,
              type: 'div',
              params: {
                className: 'new-expense-apportion new-expense-apportion-import'
              },
              child: null
            },
            {
              span: window.ISIE9 ? 12 : 8,
              show: true,
              type: 'div',
              params: {
                className: 'new-expense-apportion',
                onClick: this.handleAverageExpenseApportion
              },
              child: <span>{messages('expense-1.key10')/*一键均摊*/}</span>
            },
          ]
        },
        {
          key: 'application',
          show: false,
          btn: [
            {
              span: 24,
              show: true,
              type: 'ApplicationApportion',
              params: {
                flag: 'button',
              }
            }
          ]
        }
      ],
    };
  }

  renderImporter = () => {
    const { expenseReportOID, expenseTypeId, ownerOID, actualApportionAmount, amount, apportionedAmount } = this.props;
    return (
      <Importer
        triggerNode={<div>{messages('expense-1.key11')/*导入分摊*/}</div>}
        templateOptions={{
          templateList: [{
            templateName: messages('expense-1.key12')/*下载EXCEL文件*/,
            downloadUrl: `/api/apportion/template?expenseReportOID=${expenseReportOID}`,
            downFileName: messages('expense-1.key13')/*分摊模板文件*/
          }]
        }}
        uploadOptions={{
          uploadUrl: `/api/apportion/import?expenseReportOID=${expenseReportOID}&expenseTypeID=${expenseTypeId}&ownerOID=${ownerOID}`,
          uploadParams: {
            amount: actualApportionAmount || amount,
            apportionedAmount: apportionedAmount
          }
        }}
        errorTableData={this.handelImportCallBack}
      />);
  };
  //切换上传模板上传模块
  switchUpload = () => {
    this.setState({ tabKey: 'UPDATE' }, this.setState({ tabKey: null }));
  };

   getCurrencyPrecision = () => {
    const { currencyCode } = this.props;
    return queryCurrencyPrecision(currencyCode);
  };

   getActualApportionAmount = (oriAmount, amountActual) => {
    let { actualApportionAmount, amount } = this.props;
    let currencyPrecision = this.getCurrencyPrecision() || 2;

    if (typeof actualApportionAmount === 'number' || typeof amountActual === 'number') {
      if (typeof amountActual === 'number') {
        return Number(amountActual.toFixed(currencyPrecision));
      }
      return Number(actualApportionAmount.toFixed(currencyPrecision));
    } else {
      if (typeof oriAmount === 'number') {
        return Number(oriAmount.toFixed(currencyPrecision));
      }
      return Number(amount.toFixed(currencyPrecision));
    }
  };

  /**
   * 新增分摊
   */
  handleNewExpenseApportion = () => {
    let { expenseApportion, defaultExpenseApportion } = this.props;
    let defaultExpense = JSON.parse(JSON.stringify(defaultExpenseApportion));
    let accumulatorAmount = 0;
    const currencyPrecision = this.getCurrencyPrecision();
    const totalAmount = this.getActualApportionAmount();

    if (expenseApportion.length) {
      accumulatorAmount = expenseApportion
        .map(item => Number(item.amount))
        .reduce((accumulator, currentValue) => accumulator + currentValue);
    }
    defaultExpense.amount = Math.abs(totalAmount) > Math.abs(accumulatorAmount) ? (totalAmount - accumulatorAmount).toFixed(currencyPrecision) : 0;
    defaultExpense.proportion = Math.abs(totalAmount) > Math.abs(accumulatorAmount) ? (defaultExpense.amount / totalAmount).toFixed(4) : 0;
    defaultExpense.defaultApportion = false;
    defaultExpense.costCenterItems.map(item => {
      item.costCenterItemOID = null;
      item.departmentOid = null;
      item.costCenterItemName = null;
    });
    defaultExpense.apportionmentOID = null;
    defaultExpense.apportionmentLabels = [];
    expenseApportion.push(defaultExpense);
    this.props.onChange(expenseApportion);
  };

  /**
   * 一健均摊
   */
  handleAverageExpenseApportion = () => {
    let { expenseApportion } = this.props;
    let { length } = expenseApportion;
    const currencyPrecision = this.getCurrencyPrecision() || 2;
    const totalAmount = this.getActualApportionAmount();
    let handleExpenseAverage = () => {
      expenseApportion.map((item, index) => {
        if (index === 0) {
          item.amount = (totalAmount / length).toFixed(currencyPrecision);
          item.proportion = item.amount / totalAmount;
        } else {
          let middleAmount = expenseApportion
            .slice(0, index)
            .map(item => item.amount)
            .reduce((accumulator, currentValue) => Number(accumulator) - Number(currentValue), totalAmount);
          if (Math.abs(middleAmount) > 0 && Math.abs(middleAmount) <= Math.abs(totalAmount) / length) {
            item.amount = middleAmount;
          } else if (Math.abs(middleAmount) > Math.abs(totalAmount) / length) {
            index + 1 === length ? item.amount = middleAmount : item.amount = (totalAmount / length);
          } else if (totalAmount > 0 && middleAmount <= 0 || totalAmount < 0 && middleAmount >= 0) {
            item.amount = 0;
          }
          if (index <= length) {
            item.amount = item.amount.toFixed(currencyPrecision);
            item.proportion = item.amount / totalAmount;
          } else {
            item.proportion = item.amount / totalAmount;
            item.amount = item.amount.toFixed(currencyPrecision);
          }
        }
      });
      this.props.onChange(expenseApportion);
    };

    (length === 0 || length === 1) ? message.warning(messages('expense-1.key14')/*请先新增分摊行*/) : handleExpenseAverage();
  };

//处理导入回调
  handelImportCallBack = (result) => {
    let resultDom = null;
    if (result.success) {
      let { expenseApportion, invoiceOID } = this.props;
      let amount = this.getActualApportionAmount();
      result.message && message.info(result.message);
      resultDom = (
        <div>{messages('expense-1.key15',{arg1: result.result.length})/*导入成功：{arg1}条*/}</div>
      );
      if (result.result.length > 0) {
        result.result.map((item) => {
          item.proportion = (item.amount / amount).toFixed(4);
          item.expenseOID = invoiceOID;
          expenseApportion.push(item);
        });
        this.setState({ expenseApportion });
        this.props.onChange(expenseApportion);
      }
    } else {
      let errorColumns = [
        {
          title: messages('expense-1.key16')/*行号*/,
          dataIndex: 'rowNum',
          width: '13%'
        },
        {
          title: messages('expense-1.key17')/*错误信息*/,
          dataIndex: 'errorMessage',
          render: (value) => <Popover content={value}>{value}</Popover>
        }];
      resultDom = (
        <div>
          <div>
            {
              result.result[0].rowNum === '-'
                ? <section>{messages('expense-1.key18')/*导入失败*/}</section>
                : <section>
                  {result.result.length}{messages('expense-1.key19')/*行导致导入失败*/}
                  <a style={{ fontSize: 14, marginLeft: 10 }}
                     onClick={() => this.switchUpload(true)}> {messages('expense-1.key20')/*请修改后重新导入*/}
                  </a>
                </section>
            }
          </div>
          <div>
            <Table
              rowKey={record => record.index}
              columns={errorColumns}
              dataSource={result.result}
              pagination={false}
              bordered
              size="small"
            />
          </div>
        </div>
      );
    }
    return resultDom;
  };

  handleApplicationChange = (expenseApportion) => {
    this.props.onChange(expenseApportion);
  };

  renderBtn = (item) => {
    const { expenseReportOID, currencyCode, expenseTypeId, defaultExpenseApportion, expenseApportion, invoiceOID } = this.props;
    if (item.type === 'ApplicationApportion') {
      item.params = {
        ...item.params,
        invoiceOID,
        currencyCode,
        expenseTypeId,
        expenseApportion,
        expenseReportOID,
        defaultExpenseApportion,
        handleApplicationChange: this.handleApplicationChange
      };
    }
    return React.createElement(this.component[item.type], item.params, item.child);
  };

  render() {
    const { btnFeats} = this.state;
    const { isApplication, isReadOnly, isOccupiedBudget } = this.props;
    btnFeats.map(item => {
      if (item.key === 'expense') {
        item.show = isReadOnly;
        item.btn[1].child = this.renderImporter();
      }

      if (item.key === 'application') {
        item.show = isApplication && isOccupiedBudget;
      }
      return item;
    });
    return (
      <section>
        {
          btnFeats.map(feats => {
            return (
              <If value={feats.show}>
                <Row>
                  {
                    feats.btn.map(item => {
                      return (
                        <If value={item.show}>
                          <Col span={item.span}>
                            {this.renderBtn(item)}
                          </Col>
                        </If>
                      );
                    })
                  }
                </Row>
              </If>
            );
          })
        }
      </section>
    );
  }

}

export default ApportionFeatures;
